package api

import (
	"drama-go/internal/pkg/upload"
	"drama-go/internal/service"
	"github.com/gin-gonic/gin"
	"github.com/worryry/8-pigeons/pkg/convert"
	"github.com/worryry/8-pigeons/pkg/logger"
	"github.com/worryry/8-pigeons/pkg/server/errcode"
	"github.com/worryry/8-pigeons/pkg/server/httpServer/response"
)

func Upload(c *gin.Context) {
	file, fileHeader, err := c.Request.FormFile("file")
	fileType := convert.StrTo(c.PostForm("type")).MustInt()

	if err != nil {
		response.ToErrResponse(c, errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	if fileHeader == nil || fileType <= 0 {
		response.ToErrResponse(c, errcode.InvalidParams)
		return
	}

	fileInfo, err := service.UploadFile(upload.FileType(fileType), file, fileHeader)
	if err != nil {
		logger.Errorf("svc uploadFile err: %v", err)
		response.ToErrResponse(c, errcode.InvalidParams.WithDetails(err.Error()))
		return
	}

	response.ToSuccess(c, gin.H{
		"file_url":  "/" + fileInfo.Path,
		"file_name": fileInfo.Name,
	})
}
